const db = require('../../db/index')
const { isUrl } = require('../../utils/util')
const APP_CONFIG = require('../../utils/config') 
// 获取全部的tag列表
exports.deleteTag = (req,res) => {
    let {tagId} = req.body
    if(tagId) {
        tagId = tagId.split(',')
        let findSql =  "select tagArticles from tags where tagId in (?)"
        db.query(findSql,[tagId],(err,result) => {
            if(err) return res.send({code:500,message:err.sqlMessage})
            if(result.length == 0) return res.send({code:400,message:'未找到标签,请刷新重试'})
            let done = true
            result.forEach(item => {
                console.log(item.tagArticles)
                if(item.tagArticles){
                    done = false
                }
            })
            console.log('done',done)
            done == true ? deleteTagHandler(tagId,req,res) : res.send({code:400,message:'该标签下有文章，不能删除'})
        })
    }else {
        return res.send({code:400,message:'删除的标签id不能为空'})
    }
}


// 删除的处理函数
let deleteTagHandler = (tagId,req,res) => {
    let deleteSql = "DELETE FROM tags where tagId in (?)"
    db.query(deleteSql,[tagId],(error,response) => {
        if(error) return res.send({code:500,message:error.sqlMessage})
        if(response.affectedRows > 0) return res.send({code:200,message:'删除标签成功'})
        res.send({code:400,message:'删除标签失败'})
    })
}


exports.addTag = (req,res) => {
    let {tagName,tagDesc,tagAlias} = req.body
    if(!tagName || tagName == '') return res.send({code:400,message:'标签名不符合要求'})
    if(!tagDesc || tagDesc == '') return res.send({code:400,message:'标签介绍不符合要求'})
    tagAlias = tagAlias ? tagAlias : tagName
    let addSql = "INSERT INTO tags (tagName,tagDesc,tagAlias) VALUES (?,?,?)"
    db.query(addSql,[tagName,tagDesc,tagAlias],(error,response) => {
        if(error){
            if(error.sqlState == '23000') return res.send({code:400,message:'标签名已存在'})
            return res.send({code:500,message:err.sqlMessage})
        }
        return res.send({code:200,message:'添加标签成功',tag:{id:response.insertId,tagName,tagDesc,tagAlias}})
    })
}

exports.getTagsList = (req,res) => {
    let findSql = "select * from tags"
    try {
        db.query(findSql,(err,result) => {
            if(err) return res.send({code:500,message:err.sqlMessage})
            return res.send({code:200,message:'获取标签列表成功',tags:result})
        })
    }catch (e) {
        res.send({code:400,message:e.message})
    }
}

/*获取当前tag下面的文章列表*/
exports.getTagArticleList = (req,res) => {
    let {tagId,page,pageSize} = req.query
    tagId ? tagId = tagId*1 : null
    page = page ? page*1 : 1
    pageSize = pageSize ? pageSize*1 : 10
    let startIndex = (page - 1) * pageSize
    let endIndex = pageSize
    let count = 0
    let selectCountSql = "SELECT COUNT(s.articleId) FROM (SELECT * from articles WHERE FIND_IN_SET(articleId,(SELECT tagArticles from tags WHERE tagId = ?))) as s"
    let noCateIdCountSql = "SELECT COUNT(articleId) FROM articles"
    // 查询的sql
    let selectSql = tagId ? `
        SELECT 
        a.articleId,
        a.articleTitle,
        a.articleContent,
        a.publicTime,
        a.publicUserId,
        a.likeCount,
        a.repliesCount,
        a.viewsCount,
        GROUP_CONCAT(DISTINCT c.cateId) AS cateIds,
        GROUP_CONCAT(DISTINCT c.cateName) AS cateNames,
        GROUP_CONCAT(DISTINCT t.tagId) AS tagIds,
        GROUP_CONCAT(DISTINCT t.tagName) AS tagNames,
        a.articleCover,
        a.articleDesc,
        u.userId,
        u.userAvatar,
        u.userIp,
        u.userName,
        u.userParty
    FROM (
        SELECT *
        FROM articles
        WHERE FIND_IN_SET(articleId, (SELECT tagArticles FROM tags WHERE tagId = ${tagId}))
    ) AS a
    INNER JOIN users AS u ON a.publicUserId = u.userId
    INNER JOIN cates AS c ON FIND_IN_SET(c.cateId, a.cates)
    LEFT JOIN tags AS t ON FIND_IN_SET(t.tagId, a.tags)
    GROUP BY a.articleId order by a.publicTime DESC limit ${startIndex},${endIndex}
    `:
    `
       SELECT 
        a.articleId,
        a.articleTitle,
        a.articleContent,
        a.publicTime,
        a.publicUserId,
        a.likeCount,
        a.repliesCount,
        a.viewsCount,
        GROUP_CONCAT(DISTINCT c.cateId) AS cateIds,
        GROUP_CONCAT(DISTINCT c.cateName) AS cateNames,
        GROUP_CONCAT(DISTINCT t.tagId) AS tagIds,
        GROUP_CONCAT(DISTINCT t.tagName) AS tagNames,
        a.articleCover,
        a.articleDesc,
        u.userId,
        u.userAvatar,
        u.userIp,
        u.userName,
        u.userParty
    FROM (
        SELECT *
        FROM articles
    ) AS a
    INNER JOIN users AS u ON a.publicUserId = u.userId
    INNER JOIN cates AS c ON FIND_IN_SET(c.cateId, a.cates)
    LEFT JOIN tags AS t ON FIND_IN_SET(t.tagId, a.tags)
    GROUP BY a.articleId order by a.publicTime DESC limit ${startIndex},${endIndex}`
    db.query(tagId ? selectCountSql : noCateIdCountSql,[tagId],(err,result) =>{
        if(err) return  res.send({code:400,message:err.sqlMessage})
        count = tagId ? result[0]['COUNT(s.articleId)'] : result[0]['COUNT(articleId)']
        db.query(selectSql,(err,result) => {
            // console.log('res',result)
            if(err) return  res.send({code:400,message:err.sqlMessage})
            result.forEach(item => {
                let {tagIds,tagNames,cateIds,cateNames} = item
                item.tagIds = tagIds ? tagIds.split(',') : []
                item.tagNames = tagNames ? tagNames.split(',') : []
                item.cateIds = cateIds ? cateIds.split(',') : []
                item.cateNames = cateNames ? cateNames.split(',') : []
                item.articleCover = isUrl(item.articleCover) ? item.articleCover : APP_CONFIG.imagePrefixe + item.articleCover
                let tags = []
                for(let i = 0 ; i < item.tagIds.length;i++){
                    let obj = {tagId:'',tagName:''}
                    obj.tagId = item.tagIds[i]
                    obj.tagName = item.tagNames[i]
                    tags.push(obj)
                }
                let cates = []
                for(let i = 0 ; i < item.cateIds.length ;i++){
                    let obj = {cateId:'',cateName:''}
                    obj.cateId = item.cateIds[i]
                    obj.cateName = item.cateNames[i]
                    cates.push(obj)
                }
                item.tags = tags
                item.cates = cates
            })
            res.send({code:200,message:'查询标签列表成功',articles:result,count})
        })
    })
}